package com.example.kits;

import android.os.Handler;
import android.os.Looper;

/**
 * 主线程执行器
 */
public class Main {

    private static Handler mainHandler;

    /**
     * 在主线程执行任务
     * @param run 待执行任务
     */
    public static void run(Runnable run) {
        mainHandler().post(run);
    }

    /**
     * 在主线程重复执行任务，直至任务返回 false
     * @param call 任务
     * @param delayMills 执行间隔
     */
    public static void repeat(Callable call, long delayMills) {
        mainHandler().postDelayed(() -> {
                if (call.run()) {
                    repeat(call, delayMills);
                }
            }, delayMills);
    }

    public interface Callable {

        boolean run();

    }

    private static synchronized Handler mainHandler() {
        if (mainHandler == null) {
            mainHandler = new Handler(Looper.getMainLooper());
        }
        return mainHandler;
    }

}
